const express = require('express')
// 导入广告数据模块
const advertModel = require('../../model/advertModel')
const router = express.Router()
// 导入上传图片的包
const multer = require('multer')
const config = require('../../config/default')
const HostUrl = `${config.PROTOCOL}://${config.HOST}:${config.PORT}`
// 引入jwt token工具
const JwtUtil = require('../../utils/jwt')
const getCreateTime = require('../../utils/getCreateTime')
const { v4: uuidv4 } = require('uuid')
// 设置文件上传存储路径
// var uploadDir = `./public/uploads/${moment().format('YYYYMMDD')}`;
// 如果父目录不存在会就先创建（recursive使用递归创建目录）
// fs.mkdirSync(uploadDir, {recursive: true}); 
// 通过filename属性定制
let storage = multer.diskStorage({
    // 保存的路径
    destination(req, file, callback) {
        // callback(null, uploadDir)
        callback(null, 'public/upload/')
    },
    filename(req, file, callback) {
        // 将保存文件名设置为 字段名 + 时间戳，比如 logo-1478521468943
        let suffix = file.mimetype.split('/')[1]; //获取文件格式
        callback(null, file.fieldname + '-' + Date.now() + '.' + suffix);
    }
})
// 生成的图片放入uploads文件夹下
let upload = multer({ storage: storage })
// 1.0 发布广告的接口
router.post('/publish', upload.single('photo'), function (req, res) {
    // 参数： advert_id,advert_title,advert_href,advert_position,advert_src,advert_create_time,user_id,advert_text
    // 接收前端的文件
    let file = req.file
    // 定义存在在服务器的图片的路径（存在数据库的路径）
    let advert_src = `${HostUrl}/upload/${file.filename}`
    // 请求需要进行token校验 
    let token = req.body.token
    let jwt = new JwtUtil(token)
    let result = jwt.verifyToken()
    let advert_id = uuidv4() || Math.random().toString().slice(2)
    // 接收前端的参数
    let advert_title = req.body.advert_title || ''
    let advert_href = req.body.advert_href || ''
    let advert_text = req.body.advert_text
    let advert_position = req.body.advert_position || "1"
    let advert_create_time = req.body.advert_create_time || getCreateTime.now()//  用户创建的时间 （'2023-01-15 00:00:00'）
    if (result == 'err') {
        res.send({
            code: -1,
            msg: '登录已过期,请重新登录。'
        })
    } else {
        if (result.data) {
            let user_id = result.data
            // 调用发布广告的方法
            advertModel.publish(advert_id, advert_title, advert_href, advert_position, advert_src, advert_create_time, user_id, advert_text)
                .then(
                    data => {
                        res.send(data)
                    }
                )
                .catch(
                    err => {
                        res.send({ code: 500, msg: '服务器异常...', err })
                    }
                )
        }
    }
})
// 2.0 修改广告
router.post('/modify', upload.single('photo'), function (req, res) {
    // 接收前端的文件
    let file = req.file
    if (file == undefined) {
        res.send({
            code: -1,
            msg: "请求选择器一张图片。"
        })
    } else {
        // 定义存在在服务器的图片的路径（存在数据库的路径）
        let advert_src = `${HostUrl}/upload/${file.filename}`
        // 请求需要进行token校验 
        let token = req.body.token
        let jwt = new JwtUtil(token)
        let result = jwt.verifyToken()
        // 接收前端的参数
        let advert_id = req.body.advert_id
        let advert_title = req.body.advert_title || ''
        let advert_href = req.body.advert_href || ''
        let advert_position = req.body.advert_position || 10
        let advert_create_time = req.body.advert_create_time || getCreateTime.now()//  用户创建的时间 （'2023-01-15 00:00:00'）
        if (result == 'err') {
            res.send({
                code: -1,
                msg: '登录已过期,请重新登录'
            })
        } else {
            if (result.data) {
                // 调用修改广告方法
                advertModel.modify(advert_id, advert_title, advert_href, advert_position, advert_src, advert_create_time)
                    .then(
                        data => {
                            res.send(data)
                        }
                    )
                    .catch(
                        err => {
                            res.send({ code: 500, msg: '服务器异常...', err })
                        }
                    )
            }
        }
    }

})
// 3.0 删除广告接口
// 参数：token ,advert_id 
router.post('/remove', async (req, res) => {
    let advert_id = req.body.advert_id
    // 请求需要进行token校验 
    let token = req.body.token
    let jwt = new JwtUtil(token)
    let result = jwt.verifyToken()
    if (result == 'err') {
        res.send({
            code: -1,
            msg: '登录已过期,请重新登录。'
        })
    } else {
        if (result.data) {
            // 调用删除图片方法
            await advertModel.remove(advert_id)
                .then(
                    data => {
                        res.send(data)
                    }
                )
                .catch(
                    err => {
                        res.send({ code: 500, msg: '服务器异常...', err })
                    }
                )
        }
    }
})
// 4.0 获取广告列表接口
router.get('/list', async (req, res) => {
    // 调用获取广告列表的方法
    await advertModel.list()
        .then(
            data => {
                res.send(data)
            }
        )
        .catch(
            err => {
                res.send({ code: 500, msg: '服务器异常...', err })
            }
        )
})
// 5.0 查询广告详情接口
router.get('/detail', async (req, res) => {
    // 接收前端传递
    let advert_id = req.query.advert_id;
    let token = req.query.token;
    // 请求需要进行token校验 
    let jwt = new JwtUtil(token);
    // 返回一个对象 
    let result = jwt.verifyToken();
    // 验通过执行下一步，否则就返回登陆信息不正确
    if (result == 'err') {
        res.send({
            code: -1,
            msg: '登录已过期,请重新登录'
        });
    } else {
        if (result.data) {
            // 调用获取广告列表的方法
            await advertModel.detail(advert_id)
                .then(
                    data => {
                        res.send(data)
                    }
                )
                .catch(
                    err => {
                        res.send({ code: 500, msg: '服务器异常...', err })
                    }
                )
        }
    }

})
// 6.0 搜索广告接口
router.get('/search', async (req, res) => {
    let keyword = req.query.keyword;
    // 多字段模糊查询
    // 调用获取广告列表的方法
    await advertModel.search(keyword)
        .then(
            data => {
                res.send(data)
            }
        )
        .catch(
            err => {
                res.send({ code: 500, msg: '服务器异常...', err })
            }
        )
})
// 7.0 搜索广告接口
// 参数：token ,advert_id 
router.post('/delete', async (req, res) => {
    let advert_id = req.body.advert_id
    // 请求需要进行token校验 
    let token = req.body.token
    let jwt = new JwtUtil(token)
    let result = jwt.verifyToken()
    if (result == 'err') {
        res.send({
            code: -1,
            msg: '登录已过期,请重新登录。'
        })
    } else {
        if (result.data) {
            // 调用删除图片方法
            await advertModel.delete(advert_id)
                .then(
                    data => {
                        res.send(data)
                    }
                )
                .catch(
                    err => {
                        res.send({ code: 500, msg: '服务器异常...', err })
                    }
                )
        }
    }
})
module.exports = router;